﻿#include "EnemyPlane.h"
#include<qtimer.h>
#include<qdebug.h>
#include"WeaponBank.h"
EnemyPlane::EnemyPlane() :Plane(),
	 m_AutoBulletTimer(new QTimer)
{
	//qDebug() << "1";
	init();
}

EnemyPlane::EnemyPlane(int x, int y) :Plane(x,y),
m_AutoBulletTimer(new QTimer)
{
	//qDebug() << "2";
	init();
}

EnemyPlane::EnemyPlane(QPoint pos):Plane(pos),
m_AutoBulletTimer(new QTimer)
{
	//qDebug() << "3";
	init();
}

EnemyPlane::~EnemyPlane()
{
	//qDebug() << "释放";
	if (m_AutoBulletTimer != nullptr)
	{
		delete m_AutoBulletTimer;
		m_AutoBulletTimer = nullptr;
	}
}

void EnemyPlane::init()
{
	m_temp = getCurrentTime();
	setType(Entity::Type::enemyPlane);
	m_WeaponBank = nullptr;
	m_AutoBulletTimer->callOnTimeout([this]() {AutoBullet(); });
}

void EnemyPlane:: update()
{
	// 超出屏幕自动释放
	if (!getModelRect().intersects(m_Window))
	{
		destroy();
	}
	return Plane::update();
	//qDebug() << getWeaponBank();
	
}

void EnemyPlane::draw(QPainter* painter)
{
	return Plane::draw(painter);
}

void EnemyPlane::AutoMove()
{
	if (m_pause)
		m_temp = getCurrentTime();
	if (!isActive() || getHp() <= 0|| m_pause)
		return;
	qreal len = m_Steplength * (getCurrentTime() - m_temp) / 1000.0;
	if (len < 1.0)
	{
		m_SumLen += len;
	}
	if (m_SumLen > 1.0)
	{
		len = m_SumLen;
		m_SumLen = 0;
	}

	m_temp = getCurrentTime();
	QPoint pos(m_vector.x() * len, m_vector.y() * len);
	move(getPos() + pos);
	setCollider(getModelRect());
	if (m_approach)
	{
		m_approach = false;
		m_vector.setX(0);
	}
}

void EnemyPlane::approach(const QPoint& pos)
{
	m_approach = true;
	if (getCenterPos().x() > pos.x())
	{
		//qDebug() << "向左";
		m_vector.setX(-1);
	}
		
	else
	{
		//qDebug() << "向右";
		m_vector.setX(1);
	}
		
}

void EnemyPlane::setScore(const int score)
{
	m_Score = score;
}

const int EnemyPlane::getScore(bool one)
{
	//只获取一次模式
	if (one)
	{
		//只获取一次，获取后置为真
		if (m_ScoreOneGain)
		{
			return 0;
		}
		else
		{
			m_ScoreOneGain = true;
		}
	}
	return m_Score;
}

void EnemyPlane::setAutoBullet(bool flag,int time)
{
	//qDebug() << time;
	m_AutoBullet = flag;
	if (time > 0)
	{
		m_AutoBulletTimer->start(time);
	}
	if (!flag)
		m_AutoBulletTimer->stop();
}

void EnemyPlane::AutoBullet()
{
	if (m_WeaponBank == nullptr)
	{
		OutInfo;
		qDebug() << "武器库为创建。无法发射子弹";
	}
	int x = getCenterPos().x();
	int y = getPos().y() + getSize().height() / 2;
	getWeaponBank()->addBullet(x,y);
	/*if (!m_AutoBullet)
		return;*/
}


